<template>
  <div>
    <panel-top :earn="earn" :pay_amount="pay_amount" :yesterdayearn="yesterdayearn" :per="per" :loading="paymentInfo_init_loading"/>
    <!-- <div class="panel-top">
        <div class="item-title clearfix">
          <div class="name fl">{{$t('income.today_income')}}</div>
          <div class="button-box fr">
            <button :class="{active:showTodayData}" @click="showTodayData = true;">{{$t('dashboard.show')}}</button>
            <button :class="{active:!showTodayData}" @click="showTodayData = false;">{{$t('dashboard.hide')}}</button>
          </div>
        </div>
        <div class="item-content">
          <div class="item">
            <div class="item-top">
              <cu :val="total_rewards | num" :decimals="8" class="val" v-show="showTodayData"></cu>
              <span class="val" v-show="!showTodayData">**********</span>
              <span class="unit">BTC</span>
            </div>
            <div class="item-bottom">
              <span class="name">{{$t('income.total_income')}}</span>
            </div>
          </div>
          <div class="item">
            <div class="item-top">
              <cu :val="pps_rewards | num" :decimals="8" class="val" v-show="showTodayData"></cu>
              <span class="val" v-show="!showTodayData">**********</span>
              <span class="unit">BTC</span>
            </div>
            <div class="item-bottom">
              <span class="name">PPS{{$t('dashboard.income')}}</span>
            </div>
          </div>
          <div class="item">
            <div class="item-top">
              <cu :val="pplns_rewards | num" :decimals="8" class="val" v-show="showTodayData"></cu>
              <span class="val" v-show="!showTodayData">**********</span>
              <span class="unit">BTC</span>
            </div>
            <div class="item-bottom">
              <span class="name">PPLNS{{$t('dashboard.income')}}</span>
            </div>
          </div>
        </div>
      </div> -->

    <section class="table-box" v-loading="tableLoading" :element-loading-text="$t('unit.loading')">
      <div class="header">
        <span>{{$t('income.history_income')}}</span>
        <!-- <div class="area">
          <span :class="{active:status==='all'}" @click="changetag('all')">{{$t('income.history_income')}}</span> -->
          <!-- <span :class="{active:status==='fpps'}" @click="changetag('fpps')">PPS{{$t('dashboard.income')}}</span>
            <span :class="{active:status==='pplns'}" @click="changetag('pplns')">PPLNS{{$t('dashboard.income')}}</span> -->
        <!-- </div> -->
        <div class="excel" @click="excel">
          <spinner v-if="excelLoading" />
          <span v-else>{{$t('income.excel')}}</span>
        </div>
      </div>
      <table>
        <thead>
          <tr>
            <template v-if="status==='all'">
                <th class="pointer" @click="sortChange('day', 1)">{{$t('income.date')}}
                <i class="iconfont" :class="[sort1==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i>
              </th>
              <th class="pointer" @click="sortChange('difficulty', 2)">{{$t('income.difficulty')}}
                <i class="iconfont" :class="[sort2==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i>
              </th>
              <th class="pointer" @click="sortChange('hash_rate', 3)">{{$t('income.hash_rate_per')}}
                <i class="iconfont" :class="[sort3==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i>
              </th>
              <th class="pointer" @click="sortChange('total_rewards', 4)">{{$t('income.total_rewards')}}
                <i class="iconfont" :class="[sort4==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i>
              </th>
              <th class="pointer">{{$t('income.income_method')}}</th>
              <!-- <th class="pointer" @click="sortChange('pps_rewards', 5)">PPS{{$t('dashboard.income')}}<i class="iconfont" :class="[sort5==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i></th>
                <th class="pointer" @click="sortChange('pplns_rewards', 6)">
                  <el-tooltip class="item" effect="dark" :content="$t('income.pplns_rewards_info')" placement="top">
                    <i class="iconfont icon-yduigantanhaokongxin"></i>
                  </el-tooltip>
                  PPLNS{{$t('dashboard.income')}}
                  <i class="iconfont" :class="[sort6==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i>
                </th> -->
              <!-- <th class="pointer" @click="sortChange('mut', 7)"> -->
              <!-- <el-tooltip class="item" effect="dark" content="根据当前实时币价，折算成BTC约等于XXX.XXXXXXXXBTC" placement="top">
                    <i class="iconfont icon-yduigantanhaokongxin"></i>
                  </el-tooltip> -->
              <!-- 额外增收
                  <i class="iconfont" :class="[sort7==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i>
                </th> -->
            </template>

            <template v-if="status==='fpps'">
              <th>{{$t('income.start_time')}}</th>
              <th>{{$t('income.end_time')}}</th>
              <th class="pointer" @click="sortChange('hash_rate', 9)">{{$t('home.force')}}
                <i class="iconfont" :class="[sort9==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i>
              </th>
              <th class="pointer" @click="sortChange('shares_1h', 10)">{{$t('income.work_persent')}}
                <i class="iconfont" :class="[sort10==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i>
              </th>
              <th class="pointer" @click="sortChange('reject_rate', 11)">{{$t('dashboard.income')}}
                <i class="iconfont" :class="[sort11==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i>
              </th>
            </template>
            <template v-if="status==='pplns'">
              <th class="pointer" @click="sortChange('worker_name', 12)">{{$t('income.start_time')}}
                <i class="iconfont" :class="[sort12==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i>
              </th>
              <th class="pointer" @click="sortChange('shares_5m', 13)">{{$t('income.end_time')}}
                <i class="iconfont" :class="[sort13==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i>
              </th>
              <th class="pointer" @click="sortChange('shares_1h', 14)">{{$t('home.force')}}
                <i class="iconfont" :class="[sort14==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i>
              </th>
              <th class="pointer" @click="sortChange('shares_1h', 15)">{{$t('income.work_persent')}}
                <i class="iconfont" :class="[sort15==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i>
              </th>
              <th class="pointer" @click="sortChange('reject_rate', 16)">{{$t('dashboard.income')}}
                <i class="iconfont" :class="[sort16==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i>
              </th>
            </template>
          </tr>
        </thead>
        <tbody>
          <template v-if="total_count">
            <tr v-for="(item, index) in tableData" :key="index">
              <template v-if="status==='all'">
                <td>{{item.day}}</td>
                <td>{{(item.difficulty / 1000000000000).toFixed(3)}} T</td>
                <td>{{item.hash_rate}} {{item.unit}}</td>
                <td>{{item.total_rewards / 100000000}} BTC</td>
                <td>{{item.balance_type}}</td>
                <!-- <td>{{item.pps_rewards / 100000000}} BTC</td>
                  <td>{{item.pplns_rewards / 100000000}} BTC</td>
                  <td> -->
                <!-- <p>{{item.pplns_rewards / 100000000}} BUC</p> -->
                <!-- <p>{{item.pplns_rewards / 100000000}} MUT</p>
                  </td> -->
              </template>
              <template v-if="status==='fpps'">
                <td>{{item.start_time}}</td>
                <td>{{item.end_time}}</td>
                <td>{{item.hash_rate}} {{item.unit}}</td>
                <td>{{item.share_rate}}%</td>
                <td>{{item.total_rewards / 100000000}} BTC</td>
              </template>
              <template v-if="status==='pplns'">
                <td>{{item.start_time}}</td>
                <td>{{item.end_time}}</td>
                <td>{{item.hash_rate}} {{item.unit}}</td>
                <td>{{item.share_rate}}%</td>
                <td>{{item.total_rewards / 100000000}} BTC</td>
              </template>
            </tr>
          </template>
          <template v-else>
            <tr>
              <td :colspan="status==='all' ? 7 : 5">{{$t('unit.no_data')}}</td>
            </tr>
          </template>
        </tbody>
      </table>
    </section>
    <Pagination :page="page | num" :pageSize="pagesize | num" :totalCount="total_count | num" :disabled="tableLoading" :sizeChange="sizeChange" :currentChange="currentChange" />
  </div>
</template>
<script>
import {
  paymentInfo,
  getHistoryProfit,
  getTypeProfit,
  historyProfitExcel } from '@/api';
import { mapGetters } from 'vuex';
import Spinner from '@/components/Spinner';
import Pagination from '@/components/Pagination';
import fileDownload from 'js-file-download';
// import cu from '@/components/CountUp';

import panelTop from './common/panelTop';

export default {
  components: {
    panelTop,
    Spinner,
    Pagination,
  },
  data() {
    return {
      timer: undefined,
      earn: '',
      pay_amount: '',
      yesterdayearn: '',
      per: '',
      paymentInfoLoading: false,
      paymentInfo_init_loading: true,

      showTodayData: false,
      total_rewards: '',
      pps_rewards: '',
      pplns_rewards: '',
      todayProfitLoading: false,
      page: 1,
      pagesize: 10,
      total_count: 0,
      order_by: 'day',
      sort: 'desc',
      sort1: 'desc',
      sort2: 'desc',
      sort3: 'desc',
      sort4: 'desc',
      sort5: 'desc',
      sort6: 'desc',
      sort7: 'desc',
      sort9: 'desc',
      sort10: 'desc',
      sort11: 'desc',
      sort12: 'desc',
      sort13: 'desc',
      sort14: 'desc',
      sort15: 'desc',
      sort16: 'desc',
      status: 'all',
      tableData: [],
      tableLoading: false,
      excelLoading: false,
    };
  },
  computed: {
    ...mapGetters(['subCuid', 'obAccessKey', 'token', 'subCoinType', 'language']),
  },
  created() {
    this.getPaymentInfo();
    this.todayProfit();
    this.historyProfit();
    this.timer = window.setInterval(() => {
      this.getPaymentInfo();
    }, 15000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    excel() {
      this.excelLoading = true;
      historyProfitExcel({
        puid: this.subCuid,
        access_key: this.obAccessKey,
        token: this.token,
        language_type: this.language === 'zh' ? 'cn' : 'en',
      })
        .then((res) => {
          try {
            const JSONdata = JSON.parse(
              String.fromCharCode.apply(null, new Uint8Array(res.data)),
            );
            if (JSONdata.errcode) {
              this.$message.error(this.$t(`api.${JSONdata.errcode}`));
            } else {
              fileDownload(res.data, 'history-profit.xls');
            }
          } catch (err) {
            fileDownload(res.data, 'history-profit.xls');
          }
          this.excelLoading = false;
          // const blob = new Blob([res.data], { type: 'application/vnd.ms-excel; charset=UTF-8' });
          // const objectUrl = URL.createObjectURL(blob);
          // window.location.href = objectUrl;
        })
        .catch((err) => {
          this.excelLoading = false;
          if (err.data && err.data.errcode) {
            this.$message.error(this.$t(`api.${err.data.errcode}`));
          } else {
            this.$message.error(this.$t('error.catchError'));
          }
        });
    },
    changetag(value) {
      this.page = 1;
      this.pagesize = 10;
      if (value === 'all') {
        this.order_by = 'day';
      } else {
        this.order_by = undefined;
      }
      this.sort = 'desc';
      this.total_count = 0;
      this.tableData = [];
      this.sort1 = 'desc';
      this.sort2 = 'desc';
      this.sort3 = 'desc';
      this.sort4 = 'desc';
      this.sort5 = 'desc';
      this.sort6 = 'desc';
      this.sort7 = 'desc';
      this.sort9 = 'desc';
      this.sort10 = 'desc';
      this.sort11 = 'desc';
      this.sort12 = 'desc';
      this.sort13 = 'desc';
      this.sort14 = 'desc';
      this.sort15 = 'desc';
      this.sort16 = 'desc';
      this.status = value;
      this.statusChange();
    },
    sortChange(val, sortIndex) {
      this.order_by = val;
      if (this[`sort${sortIndex}`] === 'asc') {
        this.sort = 'desc';
        this[`sort${sortIndex}`] = 'desc';
      } else {
        this.sort = 'asc';
        this[`sort${sortIndex}`] = 'asc';
      }
      this.statusChange();
    },
    statusChange() {
      if (this.status === 'all') {
        this.historyProfit();
      } else {
        this.typeProfit();
      }
    },
    sizeChange(pagesize) {
      this.pagesize = pagesize;
      this.statusChange();
    },
    currentChange(page) {
      this.page = page;
      this.statusChange();
    },

    todayProfit() {
      // if (this.todayProfitLoading) {
      //   return;
      // }
      // this.todayProfitLoading = true;
      // getTodayProfit({
      //   puid: this.subCuid,
      // }).then((response) => {
      //   if (response.data.status === 1) {
      //     const data = response.data.data;
      //     this.total_rewards = data.total_rewards;
      //     this.pps_rewards = data.pps_rewards;
      //     this.pplns_rewards = data.pplns_rewards;
      //   }
      //   this.todayProfitLoading = false;
      // }).catch(() => {
      //   this.todayProfitLoading = false;
      // });
    },
    historyProfit() {
      if (this.tableLoading) {
        return;
      }
      this.tableLoading = true;
      getHistoryProfit({
        puid: this.subCuid,
        page: this.page,
        pagesize: this.pagesize,
        orderBy: this.order_by,
        sort: this.sort,
      })
        .then((response) => {
          if (response.data.status === 1) {
            const data = response.data.data;
            this.tableData = data.list;
            this.total_count = data.total_num;
          }
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    typeProfit() {
      if (this.tableLoading) {
        return;
      }
      this.tableLoading = true;
      getTypeProfit({
        puid: this.subCuid,
        pagesize: this.pagesize,
        page: this.page,
        orderBy: this.order_by,
        sort: this.sort,
        type: this.status,
      })
        .then((response) => {
          if (response.data.status === 1) {
            const data = response.data.data;
            this.tableData = data.list;
            this.total_count = data.total_num;
          }
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    getPaymentInfo() {
      if (this.paymentInfoLoading) {
        return;
      }
      this.paymentInfoLoading = true;
      paymentInfo({
        puid: this.subCuid,
      })
        .then((response) => {
          if (response.data.status === 1) {
            const data = response.data.data;
            this.earn = data.earn;
            this.pay_amount = data.pay_amount;
            this.yesterdayearn = data.yesterdayearn;
            this.per = data.per;
          }
          this.paymentInfoLoading = false;
          this.paymentInfo_init_loading = false;
        })
        .catch(() => {
          this.paymentInfoLoading = false;
          this.paymentInfo_init_loading = false;
        });
    },
  },
  watch: {
    subCuid() {
      this.paymentInfo_init_loading = true;
      this.getPaymentInfo();
      this.todayProfit();
      this.historyProfit();
      this.typeProfit();
    },
  },
};
</script>
